<!--
  * 设备型号表单
-->
<template>
  <a-modal title="添加型号" :width="1000" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" :disabled="props.formType == 'view'">
      <a-row :gutter="16" class="p-b-3">
        <a-col :span="12"> 设备厂商:{{ props.rowData.manufacturerName }} </a-col>
        <a-col :span="12"> 设备类型:{{ selectDictLabel(DEVICE_TYPE, props.rowData.deviceType) }} </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <div class="p-b-3">
            产品型号
            <a-button type="primary" size="small" @click="addItem"> <PlusOutlined />添加产品型号 </a-button>
          </div>
        </a-col>
        <template v-for="(item, index) in formData.deviceModelList" :key="index">
          <a-col :span="6">
            <a-form-item :name="['deviceModelList', index, 'deviceModelName']">
              <div class="flex">
                <a-input v-model:value="item.deviceModelName" placeholder="请输入型号" />
                <a-button @click="delItem(index)" type="link"><MinusCircleOutlined /></a-button>
              </div>
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>

    <template #footer>
      <a-space v-if="props.formType != 'view'">
        <a-button @click="onReset" type="link">重置</a-button>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template></a-modal
  >
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import { cloneDeep } from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { smartSentry } from '/@/lib/smart-sentry'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { strToArr } from '/@/utils/common'
  import { deviceModelApi } from '/@/api/business/b-operation/device-model/index'
  import { validatePhoneNot } from '/@/utils/validate'
  import { DEVICE_TYPE } from '/@/constants/dict'
  import { selectDictLabel, privilege } from '/@/utils/common'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  function onReset() {
    Object.assign(formData.value, cloneDeep(formDefault))
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    Object.assign(formData.value, cloneDeep(formDefault))
    visibleFlag.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 获取表单数据 ------------------------
  async function getFormData(data) {
    const params = { dmId: data.id }
    SmartLoading.show()
    try {
      let res = await deviceModelApi.page(params)
      formData.value.deviceModelList = [...res.data]
      if (formData.value.deviceModelList.length == 0) {
        addItem()
      }
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  /* 添加产品型号、删除产品型号 商户身份信息 */
  const addItem = () => {
    formData.value.deviceModelList.push({ ...cloneDeep(deviceModelItem), dmId: props.rowData.id })
  }
  const delItem = (index) => {
    if (formData.value.deviceModelList.length <= 1) {
      return message.error('产品型号必填!')
    }
    formData.value.deviceModelList.splice(index, 1)
  }
  /* 添加产品型号、删除产品型号 商户身份信息 */
  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()
  const deviceModelItem = {
    deviceModelName: undefined, //型号
    dmId: undefined,
  }
  const formDefault = {
    deviceModelList: [{ ...deviceModelItem }], //设备型号列表
    dmId: undefined, //设备模版编号
  }

  let formData = ref(cloneDeep({ ...formDefault }))

  const rules = ref({
    manufacturerId: [{ required: true, message: '设备厂商 必填' }],
    deviceType: [{ required: true, message: '设备类型 必填' }],
    deviceModelList: computed(() => {
      let arr = []
      if (formData.value.deviceModelList && formData.value.deviceModelList.length > 0) {
        arr = formData.value.deviceModelList.map((item) => {
          return { deviceModelName: [{ required: true, message: '型号名称 必填' }] }
        })
      }
      return arr
    }),
  })

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      let data = { ...formData.value, dmId: props.rowData.id }
      await deviceModelApi.insertBatch(data)
      message.success('操作成功')
      emits('ok')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      console.log('formData.value==>', formData.value)

      if (props.open) {
        getFormData(val[0])
      }
    },
    { immediate: true },
  )
</script>
